package com.hxzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.aspect.satoken.StpMobileUtil;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.controller.mobile.address.req.AddressBookAddReq;
import com.hxzy.controller.mobile.address.req.AddressBookEditReq;
import com.hxzy.controller.mobile.address.resp.AddressBookResp;
import com.hxzy.entity.AddressBook;
import com.hxzy.mapstruct.AddressBookMapStruct;
import com.hxzy.service.AddressBookService;
import com.hxzy.mapper.AddressBookMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
* @author admin
* @description 针对表【address_book(地址管理)】的数据库操作Service实现
* @createDate 2024-02-21 11:30:40
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
    implements AddressBookService{

    /**
     * 获取默认收货地址
     * @return
     */
    @Override
    public AddressBookResp defaultAddressInfo() {
        long userId = StpMobileUtil.getLoginIdAsLong();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, MarketConstants.ACCOUT_ENABLE).eq(AddressBook::getIsDeleted,MarketConstants.ACCOUT_ENABLE);
        Optional<AddressBook> oneOpt = this.getOneOpt(queryWrapper);
        /*
         if(oneOpt.isPresent()){
            return AddressBookMapStruct.INSTANCE.convert(oneOpt.get());
        }else{
            return null;
        }
         */
        return oneOpt.map(AddressBookMapStruct.INSTANCE::convert).orElse(null);
    }

    /**
     * 当前用户所有收货地址列表
     * @return
     */
    @Override
    public List<AddressBookResp> search() {
        long userId = StpMobileUtil.getLoginIdAsLong();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted,MarketConstants.ACCOUT_ENABLE)
                .orderByAsc(AddressBook::getIsDefault);
        List<AddressBook> list = this.list(queryWrapper);

        return AddressBookMapStruct.INSTANCE.convert(list);
    }


    /**
     * 修改
     * @param req
     * @return
     */
    @Override
    public boolean editData(AddressBookEditReq req) {
        AddressBook db = this.getById(req.getId());
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        AddressBook entity = AddressBookMapStruct.INSTANCE.convert(req);
        entity.setIsDefault(db.getIsDefault());
        entity.setIsDeleted(db.getIsDeleted());
        entity.setUpdateTime(new Date());
        entity.setUpdateBy(StpMobileUtil.getMobileLoginResp().getUserName());
        return this.updateById(entity);
    }

    /**
     * 新增
     * @param req
     * @return
     */
    @Override
    public boolean addData(AddressBookAddReq req) {
        AddressBook entity = AddressBookMapStruct.INSTANCE.convert(req);

        entity.setUserId(StpMobileUtil.getLoginIdAsLong());
        entity.setCreateTime(new Date());
        entity.setCreateBy( StpMobileUtil.getMobileLoginResp().getUserName());
        entity.setIsDeleted(MarketConstants.ACCOUT_ENABLE);

        //查询当前用户是否拥有（默认的）收货地址，如果没有，如果没有默认设定收货地址
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,entity.getUserId());
        queryWrapper.eq(AddressBook::getIsDefault,MarketConstants.ACCOUT_ENABLE);
        queryWrapper.eq(AddressBook::getIsDeleted,MarketConstants.ACCOUT_ENABLE);
        long count=this.count(queryWrapper);
        //已有默认收货地址
        if(count>0){
            entity.setIsDefault(MarketConstants.ACCOUT_DISABLE);
        }else{
            //没有默认的，设定本次新增默认
            entity.setIsDefault(MarketConstants.ACCOUT_ENABLE);
        }
        return this.save(entity);
    }

    @Override
    public AddressBookResp findById(Long addressId, long userId) {
        AddressBook db = this.getById(addressId);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        if(db.getUserId() !=userId){
            throw new ServiceException(AckCode.NOT_MODIFY_OTHER_USER);
        }

        return  AddressBookMapStruct.INSTANCE.convert(db);
    }


    /**
     * 设定默认收货地址
     * @param addressId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean defaultAddress(Long addressId) {
        long userId=StpMobileUtil.getLoginIdAsLong();
        //取消所有的默认收货地址
        this.baseMapper.cancelDefaultAddress(userId);
        //设定默认地址
       long result=this.baseMapper.enableDefaultAddress(userId,addressId);
        return result>0;
    }

    /**
     * 移出操作,默认收货地址,不允许移出
     * @param id
     * @return
     */
    @Override
    public boolean delete(long id) {
        AddressBook db = this.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }
        if(!db.getUserId().equals(StpMobileUtil.getLoginIdAsLong())){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }
        if(db.getIsDefault().equals(MarketConstants.ACCOUT_ENABLE)){
            throw new ServiceException(AckCode.NOT_ALLOWED_DELETE_DEFAULT_VALUE);
        }


        db.setIsDeleted(MarketConstants.ACCOUT_DISABLE);
        db.setUpdateTime(new Date());
        db.setUpdateBy(StpMobileUtil.getMobileLoginResp().getUserName());
        return this.updateById(db);
    }
}




